import '../../core/base/base_view_model.dart';
import '../../core/http/api_response.dart';
import '../../core/http/http_client.dart';
import '../user/user_model.dart';
import 'permission_model.dart';
import 'role_model.dart';

class RoleViewModel extends BaseViewModel {
  final _httpClient = HttpClient();
  List<Role> roles = [];
  List<Role> filteredRoles = [];
  String searchKeyword = '';

  // 分页相关
  int currentPage = 1;
  int pageSize = 10;
  int totalItems = 0;

  bool get hasNextPage => currentPage * pageSize < totalItems;

  // 排序相关
  String sortField = 'created_at';
  String sortOrder = 'desc';

  Future<void> fetchRoles({int page = 1}) async {
    try {
      setBusy(true);
      final response = await _httpClient.get<PaginationData<Role>>(
        '/roles/list',
        params: {
          'page': page,
          'page_size': pageSize,
          'sort_field': sortField,
          'sort_order': sortOrder,
        },
        fromJson: (json) => PaginationData.fromJson(
          json as Map<String, dynamic>,
          (item) => Role.fromJson(item as Map<String, dynamic>),
        ),
      );

      if (response.isSuccess) {
        final paginationData = response.data!;
        roles = paginationData.list.cast<Role>();
        totalItems = paginationData.total;
        currentPage = page;
        setState(roles.isEmpty ? ViewState.empty : ViewState.idle);
      } else {
        setError(response.message);
      }
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }

  Future<void> createRole(Map<String, dynamic> roleData) async {
    try {
      setBusy(true);
      final response = await _httpClient.post<void>('/roles', data: roleData);

      if (response.isSuccess) {
        await fetchRoles(page: currentPage);
      } else {
        setError(response.message);
      }
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }

  Future<void> updateRole(int id, Map<String, dynamic> roleData) async {
    try {
      setBusy(true);
      final response = await _httpClient.put<void>('/roles/$id', data: roleData);

      if (response.isSuccess) {
        await fetchRoles(page: currentPage);
      } else {
        setError(response.message);
      }
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }

  Future<void> deleteRole(int id) async {
    try {
      setBusy(true);
      final response = await _httpClient.delete<void>('/roles/$id');

      if (response.isSuccess) {
        await fetchRoles(page: currentPage);
      } else {
        setError(response.message);
      }
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }

  Future<List<Permission>> getAllPermissions() async {
    try {
      setBusy(true);
      final response = await _httpClient.get<PaginationData<Permission>>(
        '/permissions/list',
        params: {'page': 1, 'page_size': 200},
        fromJson: (json) => PaginationData.fromJson(
          json as Map<String, dynamic>,
          (item) => Permission.fromJson(item),
        ),
      );

      if (response.isSuccess) {
        return response.data!.list;
      } else {
        setError(response.message);
        return [];
      }
    } catch (e) {
      setError(e.toString());
      return [];
    } finally {
      setBusy(false);
    }
  }

  Future<List<Permission>> getRolePermissions(int roleId) async {
    try {
      setBusy(true);
      final response = await _httpClient.get<List<Permission>>(
        '/roles/$roleId/permissions',
        fromJson: (json) => (json as List).map((item) => Permission.fromJson(item as Map<String, dynamic>)).toList(),
      );

      if (response.isSuccess) {
        return response.data as List<Permission>;
      } else {
        setError(response.message);
        return [];
      }
    } catch (e) {
      setError(e.toString());
      return [];
    } finally {
      setBusy(false);
    }
  }

  Future<void> assignPermissions(int roleId, List<int> permissionIds) async {
    try {
      setBusy(true);
      final response = await _httpClient.post<void>('/roles/$roleId/permissions',
        data: permissionIds,
      );

      if (!response.isSuccess) {
        setError(response.message);
      }
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }

  void searchRoles(String keyword) {
    searchKeyword = keyword;
    _filterRoles();
    notifyListeners();
  }

  void sortRoles(String sort) {
    final parts = sort.split('_');
    if (parts.length == 2) {
      sortField = parts[0];
      sortOrder = parts[1];
      fetchRoles();
    }
  }

  void nextPage() {
    if (hasNextPage) {
      currentPage++;
      fetchRoles();
    }
  }

  void previousPage() {
    if (currentPage > 1) {
      currentPage--;
      fetchRoles();
    }
  }

  void _filterRoles() {
    if (searchKeyword.isEmpty) {
      filteredRoles = List.from(roles);
    } else {
      filteredRoles = roles
          .where((role) =>
              role.name.toLowerCase().contains(searchKeyword.toLowerCase()) ||
              role.code.toLowerCase().contains(searchKeyword.toLowerCase()) ||
              role.remark.toLowerCase().contains(searchKeyword.toLowerCase()))
          .toList();
    }
  }
}
